"""默认配置定义

定义不同Pipeline的默认配置参数

作者: PPG算法包开发团队
版本: 2.0.0
"""

from .pipeline_config import PipelineConfig


# 自定义Pipeline默认配置（基于原有批处理代码）
DEFAULT_CUSTOM_CONFIG = PipelineConfig(
    name="custom_optimal",
    description="基于原有批处理代码的优化PPG处理配置",
    sampling_rate=25.0,
    
    preprocessing={
        "outlier_detection": {
            "enabled": True,
            "method": "median_filter",
            "window_size": 25,  # 1秒窗口
            "threshold_percentile": 95
        },
        "smoothing": {
            "enabled": True,
            "method": "savgol",
            "window_length": 21,  # 最优窗口长度
            "polynomial_order": 3
        },
        "detrending": {
            "enabled": True,
            "method": "polynomial",
            "order": 2  # 2阶多项式去趋势
        },
        "filtering": {
            "enabled": True,
            "method": "butterworth",
            "filter_type": "bandpass",
            "order": 4,
            "low_cutoff": 0.5,   # 48 BPM对应频率
            "high_cutoff": 3.0   # 180 BPM对应频率
        }
    },
    
    peak_detection={
        "method": "adaptive",
        "height_percentile": 50,  # 降低高度阈值
        "distance_min": 8,        # 减小最小间隔（0.32秒）
        "prominence_factor": 0.1, # 降低突出度要求
        "width_min": 2,           # 减小最小宽度（0.08秒）
        "heart_rate_range": [40, 150],  # 更宽松的心率范围
        "fallback_range": [30, 200]     # 备用更宽松范围
    },
    
    hrv_analysis={
        "enabled": True,
        "outlier_removal": {
            "enabled": True,
            "method": "zscore",
            "threshold": 3.0  # 3个标准差
        },
        "frequency_analysis": {
            "enabled": True,
            "resampling_rate": 4.0,  # 4Hz重采样
            # Welch参数：与脚本一致的可配置项
            "welch_nperseg": None,
            "welch_overlap": 0.5,
            "detrend_before_psd": True,
            "vlf_band": [0.0033, 0.04],  # 极低频
            "lf_band": [0.04, 0.15],     # 低频
            "hf_band": [0.15, 0.4]       # 高频
        }
    },
    
    quality_assessment={
        "enabled": True,
        "segment_analysis": {
            "enabled": True,
            "window_size": 2.0,  # 2秒窗口
            "quality_threshold_percentile": 15,  # 保留质量较好的85%
            "min_segment_duration": 3.0  # 最小段长度3秒
        },
        "snr_analysis": {
            "enabled": True
        },
        "frequency_analysis": {
            "enabled": True,
            "hr_frequency_range": [0.8, 3.0]  # 心率频段
        }
    },
    
    output_options={
        "include_processed_signal": True,
        "include_peaks": True,
        "include_heart_rates": True,
        "include_hrv": True,
        "include_quality": True,
        "include_segments": True,
        "verbose": True
    }
)


# NeuroKit2 Pipeline默认配置
DEFAULT_NEUROKIT2_CONFIG = PipelineConfig(
    name="neurokit2_standard",
    description="基于NeuroKit2的标准PPG处理配置",
    sampling_rate=25.0,
    
    preprocessing={
        "method": "neurokit2",
        "clean_method": "elgendi",  # NeuroKit2推荐的PPG清洁方法
        "clean_kwargs": {
            "sampling_rate": 25
        }
    },
    
    peak_detection={
        "method": "neurokit2",
        "peak_method": "elgendi",  # NeuroKit2峰值检测方法
        "peak_kwargs": {
            "sampling_rate": 25,
            "peakwindow": 0.111,
            "beatwindow": 0.667,
            "beatoffset": 0.02,
            "mindelay": 0.3
        },
        "heart_rate_range": [40, 180]
    },
    
    hrv_analysis={
        "enabled": True,
        "method": "neurokit2",
        "hrv_kwargs": {
            "sampling_rate": 25,
            "show": False
        },
        "frequency_analysis": {
            "enabled": True,
            "method": "welch",
            "vlf_band": [0.0033, 0.04],
            "lf_band": [0.04, 0.15],
            "hf_band": [0.15, 0.4]
        }
    },
    
    quality_assessment={
        "enabled": True,
        "method": "neurokit2",
        "quality_kwargs": {
            "sampling_rate": 25,
            "method": "zhao2018"
        }
    },
    
    output_options={
        "include_processed_signal": True,
        "include_peaks": True,
        "include_heart_rates": True,
        "include_hrv": True,
        "include_quality": True,
        "include_segments": False,
        "verbose": False
    }
)


# 快速配置预设
QUICK_CONFIGS = {
    "fast": PipelineConfig(
        name="fast_processing",
        description="快速处理配置，适用于实时或批量处理",
        sampling_rate=25.0,
        preprocessing={
            "outlier_detection": {"enabled": False},
            "smoothing": {"enabled": True, "method": "savgol", "window_length": 11, "polynomial_order": 2},
            "detrending": {"enabled": False},
            "filtering": {"enabled": True, "method": "butterworth", "filter_type": "bandpass", 
                         "order": 2, "low_cutoff": 0.8, "high_cutoff": 2.5}
        },
        peak_detection={
            "method": "simple",
            "height_percentile": 60,
            "distance_min": 10,
            "heart_rate_range": [50, 120]
        },
        hrv_analysis={"enabled": False},
        quality_assessment={"enabled": False},
        output_options={
            "include_processed_signal": False,
            "include_peaks": True,
            "include_heart_rates": True,
            "include_hrv": False,
            "include_quality": False,
            "verbose": False
        }
    ),
    
    "accurate": PipelineConfig(
        name="accurate_processing",
        description="高精度处理配置，适用于科研和医疗应用",
        sampling_rate=25.0,
        preprocessing={
            "outlier_detection": {"enabled": True, "method": "median_filter", "window_size": 50, "threshold_percentile": 99},
            "smoothing": {"enabled": True, "method": "savgol", "window_length": 31, "polynomial_order": 3},
            "detrending": {"enabled": True, "method": "polynomial", "order": 3},
            "filtering": {"enabled": True, "method": "butterworth", "filter_type": "bandpass", 
                         "order": 6, "low_cutoff": 0.4, "high_cutoff": 3.5}
        },
        peak_detection={
            "method": "adaptive",
            "height_percentile": 40,
            "distance_min": 6,
            "prominence_factor": 0.05,
            "width_min": 1,
            "heart_rate_range": [35, 160]
        },
        hrv_analysis={
            "enabled": True,
            "outlier_removal": {"enabled": True, "method": "zscore", "threshold": 2.5},
            "frequency_analysis": {"enabled": True, "resampling_rate": 8.0}
        },
        quality_assessment={
            "enabled": True,
            "segment_analysis": {"enabled": True, "window_size": 5.0, "quality_threshold_percentile": 10}
        },
        output_options={
            "include_processed_signal": True,
            "include_peaks": True,
            "include_heart_rates": True,
            "include_hrv": True,
            "include_quality": True,
            "include_segments": True,
            "verbose": True
        }
    )
}


def get_config_by_name(config_name: str) -> PipelineConfig:
    """根据名称获取预定义配置
    
    参数:
        config_name: 配置名称 ('custom', 'neurokit2', 'fast', 'accurate')
        
    返回:
        PipelineConfig: 配置对象
    """
    configs = {
        'custom': DEFAULT_CUSTOM_CONFIG,
        'neurokit2': DEFAULT_NEUROKIT2_CONFIG,
        'fast': QUICK_CONFIGS['fast'],
        'accurate': QUICK_CONFIGS['accurate']
    }
    
    if config_name not in configs:
        available = ', '.join(configs.keys())
        raise ValueError(f"未知的配置名称: {config_name}. 可用配置: {available}")
    
    return configs[config_name].copy()